<template>
	<div>
		<div class="oper-form" :class="operateType === 'check' ? 'disabled' : ''">
			<a-form-model ref="form" :model="form" :rules="rules">
				<a-form-model-item label="分群名称" prop="crowdName" class="groud-name">
					<a-input v-model.trim="form.crowdName" placeholder="请输入内容" class="name-input" />
				</a-form-model-item>
				<a-form-model-item label="更新方式" class="update-type">
					<a-radio-group v-model="form.updateType">
						<a-radio :value="1">
							<span>自动更新</span>
							<span class="radio-discr">每天凌晨更新</span>
						</a-radio>
						<a-radio :value="2">
							<span>手动更新</span>
							<span class="radio-discr">分群生成后点击“更新”按钮更新数据</span>
						</a-radio>
					</a-radio-group>
				</a-form-model-item>
				<div class="sub-title">设置分群规则</div>
				<div class="rule-wrap">
					<Logic v-model="form.crowdRules.allRelation" />
					<div class="rule-content">
						<div class="user-attr">
							<div class="head">
								<div class="title">用户属性满足</div>
								<!-- <div class="add-btn" @click="addProperty">
									<a-icon type="plus-circle" />
									添加
								</div> -->
							</div>
							<div class="item-wrap">
								<Logic
									v-model="form.crowdRules.userAttrFilter.relation"
									v-if="userAttrRelationShow"
								/>
								<div class="item-content">
									<div
										class="content"
										v-for="(condition, i) in form.crowdRules.userAttrFilter.conditions"
										:key="i"
									>
										<div class="property-content">
											<UserArttr
												:path="'form.crowdRules.userAttrFilter.conditions.' + i"
												arttrType="user"
												v-model="form.crowdRules.userAttrFilter.conditions[i]"
											/>
										</div>
										<div class="del" @click="delProperty(i)">
											<a-icon type="close" />
										</div>
									</div>
								</div>
							</div>
							<div class="out-add">
								<a-button type="primary" size="small" ghost @click="addProperty">
									<a-icon type="plus" />
									添加
								</a-button>
							</div>
						</div>
						<div class="behavior">
							<div class="head">
								<div class="title">用户行为</div>
								<!-- <div class="add-btn" @click="addBehavior">
									<a-icon type="plus-circle" />
									添加
								</div> -->
							</div>
							<div class="item-wrap">
								<Logic v-model="form.crowdRules.eventRelation" v-if="eventRelationShow" />
								<div class="item-content">
									<div
										class="content"
										v-for="(behavior, j) in form.crowdRules.eventCrowds"
										:key="j"
									>
										<div class="behavior-content">
											<span class="big-order">{{ bigOrders[j] }}</span>
											<UserBehavior
												:path="'form.crowdRules.eventCrowds.' + j"
												v-model="form.crowdRules.eventCrowds[j]"
											/>
										</div>
										<div class="del" @click="delBehavior(behavior)"><a-icon type="close" /></div>
									</div>
								</div>
							</div>
							<div class="out-add">
								<a-button type="primary" size="small" ghost @click="addBehavior">
									<a-icon type="plus" />
									添加行为
								</a-button>
							</div>
						</div>
						<div class="series">
							<div class="head">
								<div class="title">行为序列</div>
								<!-- <div class="add-btn" @click="addSeries">
									<a-icon type="plus-circle" />
									添加
								</div> -->
							</div>
							<div class="item-wrap">
								<Logic
									v-model="form.crowdRules.behaviorSeqRelation"
									v-if="behaviorSeqRelationShow"
								/>
								<div class="item-content">
									<div
										class="content"
										v-for="(series, k) in form.crowdRules.behaviorSeqVos"
										:key="k"
									>
										<div class="series-content">
											<span class="big-order">{{ bigOrders[k] }}</span>
											<BehaviorSeries
												:order="bigOrders[k]"
												v-model="form.crowdRules.behaviorSeqVos[k]"
											/>
										</div>
										<div class="del" @click="delSeries(k)"><a-icon type="close" /></div>
									</div>
								</div>
							</div>
							<div class="out-add">
								<a-button type="primary" size="small" ghost @click="addSeries">
									<a-icon type="plus" />
									添加行为序列单元
								</a-button>
							</div>
						</div>
					</div>
				</div>
				<div class="footer-btn" v-if="operateType !== 'check'">
					<a-form-model-item>
						<a-spin :spinning="loading">
							<a-button class="cancel-btn" @click="closeSelf">取消</a-button>
							<a-button type="primary" @click="onSubmit">保存</a-button>
						</a-spin>
					</a-form-model-item>
				</div>
			</a-form-model>
		</div>
	</div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
import { UserProperty, Behavior, Series, backShowData, deleteCustomAttrs } from './model'
import Logic from '../Logic.vue'
import UserArttr from './UserArttr.vue'
import UserBehavior from './UserBehavior.vue'
import BehaviorSeries from './BehaviorSeries.vue'
import { userCrowdSave, getUserCrowdInfo } from '@/api/userGroup'
import _ from 'lodash'
import { nameLength } from '../model'
@Component({
	name: 'ConditionGroup',
	components: {
		Logic,
		UserArttr,
		UserBehavior,
		BehaviorSeries
	}
})
export default class ConditionGroup extends Vue {
	@Prop() operateType!: string
	@Prop() userCrowdId!: string
	bigOrders: Array<any> = [
		'A',
		'B',
		'C',
		'D',
		'E',
		'F',
		'G',
		'H',
		'I',
		'J',
		'K',
		'L',
		'M',
		'N',
		'O',
		'P',
		'Q',
		'R',
		'S',
		'T',
		'U',
		'V',
		'W',
		'X',
		'Y',
		'Z'
	]
	public form = {
		id: null,
		projectId: null,
		showName: '',
		crowdName: '', //表单属性
		crowdRule: null,
		samplingFactor: null,
		userCount: null,
		updateType: 1, // 表单属性
		crowdType: 'condition',
		status: 1,
		createTime: null,
		updateTime: null,
		createUser: null,
		updateUser: null,
		crowdRules: {
			//表单属性
			allRelation: 'and',
			userAttrFilter: {
				//用户属性模块
				conditions: [],
				relation: 'and'
			},
			eventCrowds: [],
			eventRelation: 'and', //用户行为间的关系 and / or
			behaviorSeqRelation: 'and', //行为序列间的关系
			behaviorSeqVos: [] //行为序列
		}
	}
	rules = {
		crowdName: [
			{ required: true, message: '请输入分群名称', trigger: 'blur' },
			{ validator: nameLength, trigger: 'blur' }
		]
	}
	loading = false
	get userAttrRelationShow() {
		return this.form.crowdRules.userAttrFilter.conditions.length > 1
	}
	get eventRelationShow() {
		return this.form.crowdRules.eventCrowds.length > 1
	}
	get behaviorSeqRelationShow() {
		return this.form.crowdRules.behaviorSeqVos.length > 1
	}
	created() {
		const projectId: any = localStorage.getItem('productId')
		this.form.projectId = projectId
		if (this.operateType !== 'create') {
			this.getInfo(this.userCrowdId)
		}
	}
	closeSelf() {
		this.$emit('close')
	}
	addProperty() {
		const property = new UserProperty()
		const conditions: UserProperty[] = this.form.crowdRules.userAttrFilter.conditions
		conditions.push(property)
	}
	addBehavior() {
		const behavior = new Behavior()
		const eventCrowds: Behavior[] = this.form.crowdRules.eventCrowds
		eventCrowds.push(behavior)
	}
	addSeries() {
		const series = new Series()
		const behaviorSeqVos: Series[] = this.form.crowdRules.behaviorSeqVos
		behaviorSeqVos.push(series)
	}
	delProperty(index: number) {
		this.form.crowdRules.userAttrFilter.conditions.splice(index, 1)
	}
	delBehavior(item: never) {
		const index = this.form.crowdRules.eventCrowds.indexOf(item)
		if (index > -1) this.form.crowdRules.eventCrowds.splice(index, 1)
	}
	delSeries(index: number) {
		this.form.crowdRules.behaviorSeqVos.splice(index, 1)
	}
	onSubmit() {
		const _form = _.cloneDeep(this.form)
		const params = deleteCustomAttrs(_form)
		const formRef: any = this.$refs['form']
		formRef.validate((valid: any) => {
			if (valid) {
				this.loading = true
				userCrowdSave(params)
					.then(res => {
						const { code, message } = res
						if (code == 200) {
							this.$notify.success({
								message: `保存成功！`
							})
							this.closeSelf()
							this.$emit('handleRefresh')
						} else {
							this.$notify.warning({
								message: message
							})
						}
					})
					.catch((err: any) => {
						this.$message.error(err.msg || err.message, 5)
					})
					.finally(() => {
						this.loading = false
					})
			}
		})
	}
	async getInfo(id: string | number) {
		await getUserCrowdInfo(id).then(res => {
			const { data } = res
			const { userAttrFilter, eventCrowds, behaviorSeqVos } = data.crowdRules
			userAttrFilter.conditions.forEach((con: any) => {
				con._timeRange = [null, null]
				con._params1 = ''
				con._params2 = ''
				con._params3 = ''
			})
			eventCrowds.forEach((item: any) => {
				let fromDate = this.$moment(item.fromDate)
				let toDate = this.$moment(item.toDate)
				item._timeRange = [fromDate, toDate]
				if (item.eventAttr.attrName && item.aggregatorAlias) {
					item._aggregator = [
						{
							aggregatorCode: item.eventAttr.attrCode,
							aggregatorAlias: item.eventAttr.attrName
						},
						{
							aggregatorCode: item.aggregatorCode,
							aggregatorAlias: item.aggregatorAlias
						}
					]
				}
				item._params = item.params[0] || ''
				item._params1 = item.params[0] || ''
				item._params2 = item.params[1] || ''
				item.filter.conditions.forEach((con: any) => {
					con._timeRange = [null, null]
					con._params1 = ''
					con._params2 = ''
					con._params3 = ''
				})
			})
			behaviorSeqVos.forEach((item: any) => {
				let fromDate = this.$moment(item.fromDate)
				let toDate = this.$moment(item.toDate)
				item._timeRange = [fromDate, toDate]
				item.steps.forEach((step: any) => {
					step.filter.conditions.forEach((con: any) => {
						con._timeRange = [null, null]
						con._params1 = ''
						con._params2 = ''
						con._params3 = ''
					})
				})
			})
			backShowData(this.form, data)
		})
	}
}
</script>

<style lang="scss" scoped>
.oper-form {
	height: 100%;
	.a-form-model {
		height: 100%;
	}
	// .ant-form-item {
	// 	margin-bottom: 8px;
	// }
}
.groud-name {
	display: flex;
	.name-input {
		width: 395px;
	}
}
.update-type {
	display: flex;
	.ant-radio-group {
		display: flex;
		flex-direction: column;
	}
}
.disabled {
	pointer-events: none;
	opacity: 0.6;
}
.sub-title {
	margin-top: 12px;
	font-weight: 600;
}
.radio-discr {
	margin-left: 24px;
	opacity: 0.6;
}
.rule-wrap {
	margin-top: 12px;
	display: flex;
	.rule-content {
		flex: 1;
		& > div {
			border: 1px solid $border;
			padding: 8px;
			margin-top: 8px;
		}
		& > div:first-child {
			margin-top: 0;
		}
	}
}

.head {
	display: flex;
	justify-content: space-between;
}
.item-wrap {
	display: flex;
	.item-content {
		flex: 1;
	}
	.content {
		margin-top: 4px;
		display: flex;
		justify-content: space-between;
		.del {
			padding-top: 12px;
			width: 50px;
			height: 40px;
			text-align: center;
			cursor: pointer;
		}
		.property-content {
			flex: 1;
		}
		.behavior-content {
			flex: 1;
			display: flex;
		}
		.series-content {
			flex: 1;
			display: flex;
		}
	}
}
.footer-btn {
	padding-top: 30px;
	display: flex;
	justify-content: flex-end;
	.cancel-btn {
		margin-right: 8px;
	}
}
.big-order {
	font-size: 16px;
	color: #fff;
	display: inline-block;
	padding-left: 4px;
	padding-right: 4px;
	background: #40a9ff;
	margin-right: 4px;
	line-height: 24px;
	height: 24px;
	margin-top: 8px;
}
.out-add {
	margin-top: 4px;
}
</style>
